#!/usr/bin/python
# -*- coding: cp1250 -*-

import string, re, time

def date2iso(x):
    """
    Description : Transforms Dates in Variety of Formats to ISO Date Format (e.g. from DDMMYYYY, D\M\YY, DD\MM\YYYY, YYYY\MM\YY to  YYYY-MM-DD)
    Limitations : Not Working With: Dates in American Format MM/DD/YY;  
    """
    if len(re.sub('\d', '', x)) == 0 and len(x) == 8:
        res = x[4:]+"-"+x[2:4]+"-"+x[:2]
        
    elif len(re.sub('\D', '', x[:4] )) == 4:
                xcut = string.split(x, x[4])
                res = "%s-%s-%s"% (  xcut[0]
                                   , string.zfill(xcut[1], 2)
                                   , string.zfill(xcut[2], 2))
    else:
        i = re.sub("\d", "", x)
        deli = i[0]
        xcut = string.split(x, deli)                  
        if len(xcut[2]) == 2: YY  = "20%s"% (xcut[2])
        else: YY = xcut[2]
        res = "%s-%s-%s"% (  YY
                            , string.zfill(xcut[1], 2)
                            , string.zfill(xcut[0], 2))
    return res

def test_date2iso():
    ''' testing date2iso function

    >>> date2iso("10111983"), date2iso("06092008"), date2iso("24.12.2010")
    ('1983-11-10', '2008-09-06', '2010-12-24')
    
    >>> date2iso("3.2.08"), date2iso("03.2.08"), date2iso("3.02.08")
    ('2008-02-03', '2008-02-03', '2008-02-03')

    >>> date2iso("3.2.2008"), date2iso("03.2.2008"), date2iso("3.02.2008")
    ('2008-02-03', '2008-02-03', '2008-02-03')

    >>> date2iso("31/3/08"), date2iso("31/03/08")
    ('2008-03-31', '2008-03-31')

    >>> date2iso("31/3/2008"), date2iso("31/03/2008")
    ('2008-03-31', '2008-03-31')

    >>> date2iso("3-3-08"), date2iso("03-3-08"), date2iso("3-03-08")
    ('2008-03-03', '2008-03-03', '2008-03-03')

    >>> date2iso("3-3-2008"), date2iso("03-3-2008"), date2iso("3-03-2008")
    ('2008-03-03', '2008-03-03', '2008-03-03')

    >>> date2iso("2008-3-3"), date2iso("2008-03-3"), date2iso("2008-03-3")
    ('2008-03-03', '2008-03-03', '2008-03-03')
    '''

if __name__== '__main__':
    ''' '''
    import doctest
    doctest.testmod()
